﻿<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title th:text="#{userchat.petNetwork}">宠联网人工客服</title>
<link rel="stylesheet" type="text/css" href="./layui/css/layui.css">

<link rel="stylesheet" type="text/css" href="./userchat/font_Icon/iconfont.css">
<link rel="stylesheet" type="text/css" href="./userchat/css/chat.css">
<link rel="stylesheet" type="text/css" href="./layui/css/modules/layer/default/layer.css">
<style>
	.chatBox-send{
		width: 100%;
		position: relation;
	}
	.qqFace{
		width: 96%;
		position: absolute;	
		box-sizing: border-box;
		top: -125px;
	}
	#facebox{
		width:100%;
		overflow:auto;
	}
	#facebox::-webkit-scrollbar{
		height: 0;
	}
	#facebox::-webkit-scrollbar-thumb{
		background: transparent;
		height: 0;
	}
	.layui-btn, .layui-edge, .layui-inline, img{
		max-width: 218px;
	}
</style>
</head>
<body>


<div class="chatContainer">
    <div class="chatBox" ref="chatBox">
        <div class="chatBox-head">
            <div class="chatBox-head-two">
                <div class="chat-return"	id="back">
	                <i class="layui-icon layui-icon-return"></i>
                </div>
                <div class="chat-people"	id="chatPeople">
                    <div class="ChatInfoHead">
                        <img src="./layui/images/img/tu2.png" th:text="#{userchat.avatar}" alt="头像">
                    </div>
                    <div class="ChatInfoName" th:text="#{userchat.smallmachine}">机器小朵</div>
                </div>
                <div class="chat-kefu" th:text="#{userchat.customerservice}"> 转人工</div> 
            </div>
        </div>
            <div class="chatBox-kuang" ref="chatBoxkuang">
                <div class="chatBox-content">
                <div	class="show-sk">
                	<div class="sk-three-bounce">
			        	
			      	</div>
                </div>
                	
                    <div class="chatBox-content-demo" id="chatBox-content-demo">

                    </div>
                </div>
               
                <div class="chatBox-send">
                	<div class="qqFace">	</div>
                    <div class="div-textarea" contenteditable="true" id="text_content" >
                    </div>
                    <div>
                        <button  id="chat-biaoqing" class="btn-default-styles">
                            <i class="layui-icon layui-icon-face-smile"></i>
                        </button>
						
                        <label id="chat-tuxiang" th:text="#{userchat.sendpictures}" title="发送图片" for="inputImage" class="btn-default-styles">
                            <i class="layui-icon layui-icon-picture"></i>
                        </label>
                        <button id="chat-fasong" class="btn-default-styles"><i class="layui-icon layui-icon-release"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
<div	hidden="true" class="comment">
<input type="file" onchange="selectImg(this)" accept="image/jpg,image/jpeg,image/png"
                                   name="file" id="inputImage" >
<div class="com_form">
<textarea class="input" id="saytext" name="saytext"></textarea>
<p>
</div>
</div>


<div	id="avgrate" style="margin-bottom: 1px;margin-left: 20px;">
			<fieldset	id="username" class="layui-elem-field layui-field-title" style="margin-bottom: 1px;">
			  
			</fieldset>
			<div id="test1" th:text="#{userchat.overallrating}" >综合评分：<img alt="" src=""	id="logo"></div>
			<div id="test2"></div>
			<div>
			    <div >
			      <textarea  th:placeholder="#{userchat.pleaseinputevaluation}" placeholder="请输入评价" id="content"></textarea>
			    </div>
			</div>
			<div >
			    <div >
			      <button class="layui-btn"	id="tjpj" th:text="#{userchat.submit}">提交</button>
			    </div>
			</div>
</div>

<script src="./userchat/js/jquery.min.js"></script>
<script src="./js/base64.js"></script>
<script src="./layui/layui.js"></script>
<script src="./userchat/layer/layer.js"></script>
<script src="./userchat/js/message.js"></script>
<script src="./userchat/js/jquery.qqFace.js"></script>
<!-- <script src="/webjars/sockjs-client/1.1.2/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/2.3.3/stomp.min.js"></script> -->
<script>
	var room = null;
	var seat = null;
	var kefuList = [];
	var face = null;
	var photoUrl = null;
	var	area=null;
	$(function() {
		$('#chat-biaoqing').qqFace({
			id: 'facebox',
			assign: 'saytext',
			path: './userchat/img/arclist/' /* 表情存放的路径 */
		});
	});
	
	function showQQFace() {
		face = $("#saytext").val();
		$(".div-textarea").html(replace_em(face));
	} /* 查看结果 */
	function replace_em(str) {
		str = str.replace(/\</g, '&lt;');
		str = str.replace(/\>/g, '&gt;');
		str = str.replace(/\n/g, '<br/>');
		str = str.replace(/\[em_([0-9]*)\]/g, '<img	style="width: 24px;height: 24px;" src="./userchat/img/arclist/$1.gif" border="0" />');
		return str;
	} /* 判断用户是哪个平台的 */
	$.ajax({
		type: "POST",
		async: false,
		url: "/js/userChat/get_user",
		data: GetRequest(),
		dataType: "json",
		success: function(data) { /* {username:,token:,platForm:,area:} */
			room = 'PFU' + data.username;
			area = data.area;
			get_login_user(data.token); /* 不同平台显示的不同 */
			forPlat(data.platForm); /* 更新当天的聊天信息 */
			refresh(); /* 用户聊天页刷新时获取正在和用户聊天的客服坐席 */
			seat = 'CSD' + get_talking(data.username); /* 聊天头更新为聊天的对象 */
			if(seat.substring(3) == get_talking(data.username)) {
				$(".ChatInfoName").text(seat.substring(3));
			}
		}
	}); /* 与聊天服务器建立连接 */
	var websocket;
	if('WebSocket' in window) {
		websocket = new WebSocket(getWeSocket() + "/" +area.substring(0, 2).toLowerCase()+ "/" + room);
	} else if('MozWebSocket' in window) {
		websocket = new MozWebSocket(getWeSocket() + room);
	} else {
		websocket = new SockJS(getSockJS() + room);
	} /* 当收到消息后 */
	websocket.onmessage = function(event) {
		var data = JSON.parse(event.data);
		console.log(data);
		switch(data.header.code){
		case 1:
			kefuList.push(data.data);
			break;
		case 2:
			
			break;
		case 3:
			kefuList = data.data.CSD;
			break;
		case 4:
			if(data.data.msgType == 'Picture') {
				printCustomerImage(data.data)
			}
			if(data.data.msgType == 'Text') {
				getMessage(data.data)
			}
			break;
		case 5:
			if(data.data.res == 0) {
				alertPrompt("[[#{userchat.hastymcs}]]")
			}
			if(data.data.res == 1) {
				alertPrompt("[[#{userchat.entertatbapw}]]")
			}
			break;
		case 6:
			printKefuMessage(data.data)
			break;
		}
		
		}
	
	
	function getMessage(json) { /* 赋值坐席 */
		 /* 收到消息后更新消息为送达 */
		
		if(json.msgId!=-100){
			printKefuMessage(json);
			saveMessage(json);
			/* $.ajax({
				type: "POST",
				async: false,
				url: "/js/messageses/updateStatus",
				data: {
					sendTime: json.sendTime
				},
				dataType: "json",
				success: function(data) { /* console.log("消息状态更新："); 根据消息状态进行拼接 */
					/* if(data.res == "success") {
						printKefuMessage(json);
					}
				},
				error: function() {
					console.log('getMessage')
				},
			}); */
		}else{
			printKefuMessage(json);
		}
		
	}
	//保存消息
	function	saveMessage(json) {
		console.log(">>>>保存消息");
		console.log(json);
		$.ajax({
			type: "POST",
			async:false,
			url: "/js/messageses/saveMessage",
			data: json,
			dataType: "text",
			success: function(data) {
				console.log("消息发送")
				console.log(data)
			},
			error:function(){alert('eoo')},
		});
	}
	/* 发送数据 */
	function send() {
		var content = $(".div-textarea").html().replace(/[\n\r]/g, '<br>');
		console.log(content);
		console.log(seat);
		$("#saytext").val(""); /* 如果坐席为空则接入机器人 */
		if(seat == null || seat == 'CSDundefined') {
			printUserMessage(content);
			printUserMessageToRobot(content);
		} else {
			websocket.send(
					JSON.stringify(
							getMessageStructure(room,seat,"Text",content,room)
							));
			printUserMessage(content);
			/* var res = sendMsg(content);
			if(res.res == 0) {
				
			} */ /* 客服掉线了所以向机器人发送了一条消息 */
			/* if(res.res == 2) {
				seat = null;
				printUserMessage(content);
				var array = JSON.parse(res.data);
				printRobotMessage(array[0].values.text);
			} */
		}
	} /* 调用机器人 */
	function printUserMessageToRobot(content) {
		$.ajax({
			type: "POST",
			async: false,
			url: "/js/robot/get_message_robot",
			data: {
				content: content
			},
			dataType: "json",
			success: function(data) {
				//console.log(data);
				for(var i = 0; i < data.length; i++) {
					printRobotMessage(data[i].values.text);
				}
			},
			error: function() {
				console.log('printUserMessageToRobot')
			},
		});
	} /* 输出机器人的语句 */
	function printRobotMessage(str) {
		var Robotmessage = '<div class="clearfloat">' + '<div class="author-name">' + '<small class="chat-date">' + getNowFormatDate() + '</small>' + '</div>' + '<div class="left">' + '<div class="chat-avatars"><img src="./layui/images/img/tu2.png" alt="头像"></div>' + '<div class="chat-message">' + str + '</div>' + '</div>' + '</div>';
		$(".chatBox-content-demo").append(Robotmessage);
		refresh_bottom();
	} /* 输出用户的语句 */
	function printUserMessage(str) {
		var textContent = '<div class="clearfloat">' + '<div class="author-name">' + '<small class="chat-date">' + getNowFormatDate() + '</small>' + '</div>' + '<div class="right">' + '<div class="chat-message">' + str + '</div>' + '<div class="chat-avatars"><img src="' + photoUrl + '" alt="头像"></div>' + '</div>' + '</div>';
		$(".chatBox-content-demo").append(textContent);
		refresh_bottom();
	}
	
	function printKefuMessage(json) {
		seat = json.fromUser;
		console.log("客服赋值结果："+seat)
		 /* 改变聊天头 */
		$(".ChatInfoHead img").attr("src",json.avatar);
		$(".ChatInfoName").text(seat.substring(3));
		var kefumessage = '<div class="clearfloat">' + '<div class="author-name">' + '<small class="chat-date">' + getNowFormatDate() + '</small>' + '</div>' + '<div class="left">' + '<div class="chat-avatars"><img src="./layui/images/img/tu2.png" alt="头像"></div>' + '<div class="chat-message">' + json.content + '</div>' + '</div>' + '</div>';
		$(".chatBox-content-demo").append(kefumessage);
		refresh_bottom();
	}
	screenFuc();
	(window.onresize = function() {
		screenFuc();
	})(); /* 返回 */
	$(".chatBtn").click(function() {
		$(".chatBox").toggle(10);
	}); /* 请求客服 */
	$(".chat-kefu").click(function() { /* 如果有客服在线 */
		var len = kefuList.length;
		if(len > 0) {
			for(var i = 0; i < kefuList.length; i++) {
				var res;
				websocket.send(
						JSON.stringify(
								getMessageStructure(room,kefuList[i],"Text","人工",room)
								));
				/* $.ajax({
					type: "POST",
					async: false,
					url: "/js/messageses/sendMsg",
					data: {
						formUser: room,
						toUser: kefuList[i],
						postMessages: '人工'
					},
					dataType: "json",
					success: function(data) {
						console.log("人工请求");
						console.log(data);
						if(data.res == 0) {
							alertPrompt("已为您转接人工客服")
						}
						if(data.res == 1) {
							alertPrompt("进入待接入区请稍后")
						}
						res = data;
					},
					error: function() {
						alert('eoo')
					},
				}); */
			}
		} else {
			alertPrompt("[[#{userchat.manualcsinoptal}]]")
		}
	}); /* 发送信息 */
	$("#chat-fasong").click(function() {
		send();
	}); /* enter事件CTRL+enter换行 */
	$(function() {
		$("#text_content").focus(function() {
			$("#text_content").removeClass("flag");
		});
	});
	
	function add() {
		insertHTML("<br/><br/>");
	} /* 再加入一个全屏事件 */
	$(window).click(function(e) {
		if(window.getSelection) {
			var getevent = e.srcElement ? e.srcElement : e.target; /* 不要告诉我不知道这句的意思   */
			if(getevent.id != null && getevent.id == "cmdInsert" || getevent.id == "text_content") {} else $("#text_content").addClass("flag"); /* 除非点了那个插入html的按钮 其他时候必须要执行getFocus来更新最后失去焦点的div   */
		}
	});
	
	function insertHTML(html) {
		var dthis = $("#text_content")[0];
		var sel, range; /* console.log($(dthis).hasClass("flag")); */
		if($(dthis).hasClass("flag")) {
			$(dthis).html(dthis.innerHTML + html);
			return;
		}
		if(window.getSelection) { /* IE9 and non-IE   */
			sel = window.getSelection();
			if(sel.getRangeAt && sel.rangeCount) {
				range = sel.getRangeAt(0);
				range.deleteContents();
				var el = document.createElement('div');
				el.innerHTML = html;
				var frag = document.createDocumentFragment(),
					node, lastNode;
				while((node = el.firstChild)) {
					lastNode = frag.appendChild(node);
				}
				range.insertNode(frag);
				if(lastNode) {
					range = range.cloneRange();
					range.setStartAfter(lastNode);
					range.collapse(true);
					sel.removeAllRanges();
					sel.addRange(range);
				}
			}
		} else if(document.selection && document.selection.type != 'Control') {
			$(dthis).focus(); /* 在非标准浏览器中 要先让你需要插入html的div 获得焦点 */
			ierange = document.selection.createRange(); /* 获取光标位置 */
			ierange.pasteHTML(html); /* 在光标位置插入html 如果只是插入text 则就是fus.text="..."  */
			$(dthis).focus();
		}
	} /* enter只发送不换行 */
	$(window).keydown(function(event) {
		if(event.keyCode == 13) {
			if(event.ctrlKey) {
				add();
			} else {
				send();
				event.cancelBubble = true;
				event.preventDefault();
				event.stopPropagation();
			}
		}
	}); /* 发送表情 */
	$("#chat-biaoqing").click(function() {
		$(".biaoqing-photo").toggle();
	});
	$(document).click(function() {
		$(".biaoqing-photo").css("display", "none");
	});
	$("#chat-biaoqing").click(function(event) {
		event.stopPropagation(); /* 阻止事件 */
	}); 
	/* 发送图片 */
	function selectImg(pic) {
		if(!pic.files || !pic.files[0]) {
			return;
		}
		var reader = new FileReader();
		reader.onload = function(evt) {
			var images = evt.target.result;
			/* 接入机器人 */
			if(seat == null || seat == 'CSDundefined') {
				printUserImgToRobot(images.substr(images.indexOf(',') + 1));
				printUserImage(images);
			} else {
				var res = sendImg(images.substr(images.indexOf(',') + 1));
				if(res != null) {
					printUserImage(images);
					websocket.send(
							JSON.stringify(
									getMessageStructure(room,seat,"Picture",res,room)
									));
				}
				
			}
		};
		reader.readAsDataURL(pic.files[0]);
	}
	$(".chatBox-head-two").toggle(); /* 向机器人发图片 */
	function printUserImgToRobot(content) {
		$.ajax({
			type: "POST",
			async: true,
			url: "./js/robot/get_Img_robot",
			data: {
				data: content
			},
			dataType: "json",
			beforeSend: function() {},
			complete: function() {},
			success: function(data) {
				for(var i = 0; i < data.length; i++) {
					printRobotMessage(data[i].values.text);
				}
			},
			error: function() {
				console.log("printUserImgToRobot");
			},
		});
	}
	
	function printUserImage(images) {
		var result = '<div class="clearfloat"><div class="author-name"><small class="chat-date">' + getNowFormatDate() + '</small> </div> <div class="right"> <div class="chat-message"><img src="' + images + '"></div> <div class="chat-avatars"><img src="' + photoUrl + '" alt="头像"></div> </div> </div>';
		$(".chatBox-content-demo").append(result); /* 聊天框默认最底部 */
		$(document).ready(function() {
			$("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
		});
	};
	
	function printCustomerImage(data) {
		var path = data.content;
		var result = '<div class="clearfloat"><div class="author-name"><small class="chat-date">' + format(data.sendTime) + '</small></div><div class="left"><div class="chat-avatars"><img src="' + './userchat/img/icon01.png' + '" alt="头像"></div><div class="chat-message"><img src="' + path + '" alt=""></div></div></div>';
		$(".chatBox-content-demo").append(result); /* 聊天框默认最底部 */
		$(document).ready(function() {
			$("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
		});
		saveMessage(data);
	}
</script>
</body>
</html>

